package com.eurobcoin.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eurobcoin.worker.MailWorker;
import com.eurobcoin.worker.MailWorkerStatusModel;

@Controller
@RequestMapping("/mantenimiento")
public class MantenimientoController {

	private static final Logger logger = LoggerFactory.getLogger(MantenimientoController.class);
	
	private static final String MANTENIMIENTO_CORREO_VIEW = "mant_correo";
	
	@Autowired
	private MailWorker mailWorker;
	
	public MantenimientoController() {
		logger.info("Starting MatenimientoController.");
	}
	
	@RequestMapping(value="/correo.html", method=RequestMethod.GET)
	public ModelAndView doIndex() throws Exception {

		ModelAndView ret = new ModelAndView(MANTENIMIENTO_CORREO_VIEW);

		List<MailWorkerStatusModel> statuses = this.mailWorker.getStatus();
		ret.addObject("mailStatus", statuses);
		
		return ret;
	}
	
	@RequestMapping(value="/test_jndi_email.html", method=RequestMethod.POST)
	public ModelAndView testJndiResource(
			@RequestParam("email") String email, 
			@RequestParam("jndi") String jndi) throws Exception {
		
		logger.debug("email=" + email + "; jndi=" + jndi);
		
		ModelAndView ret = new ModelAndView(MANTENIMIENTO_CORREO_VIEW);
		
		Context ic = new InitialContext();
		Session session = (Session)ic.lookup(jndi);
		
		String body = "Test body from Eurobcoin. Sending using JNDI " + jndi;
		String subject = "Test subject from Eurobcoin";
		
		this.sendEmail(session, email, email, subject, body);
		
		List<MailWorkerStatusModel> statuses = this.mailWorker.getStatus();
		ret.addObject("mailStatus", statuses);
		
		ret.addObject("message", "El correo se ha enviado con éxito");
		
		return ret;
		
	}
	
	private void sendEmail(
			Session session,
			String toEmail, 
			String toName, 
			String subject, 
			String body) throws MessagingException, UnsupportedEncodingException {

		Message msg = new MimeMessage(session);

		msg.setSubject(subject);
		
		msg.setRecipient(RecipientType.TO,
				new InternetAddress(toEmail, toName));
		
		msg.setContent(body, "text/html; charset=UTF-8");
		
		Transport.send(msg);
	}
	
}
